<?php
declare(strict_types=1);

namespace app\controller\merchant;

use app\controller\BaseController;
use app\model\PosterTemplate;
use think\facade\{Filesystem, Validate};
use think\Image;

class PosterTemplateController extends BaseController
{
    /**
     * 允许的图片类型
     */
    protected $allowedTypes = ['image/jpeg', 'image/png'];
    
    /**
     * 图片质量
     */
    protected $quality = 80;
    
    /**
     * 获取模板列表
     */
    public function list()
    {
        $list = PosterTemplate::where('merchant_id', request()->merchant_id)
            ->order('create_time', 'desc')
            ->select();
            
        return json(['code' => 0, 'msg' => 'success', 'data' => $list]);
    }
    
    /**
     * 上传模板
     */
    public function upload()
    {
        $file = request()->file('image');
        $name = input('name/s', '');
        $qrcodePosition = input('qrcode_position/a');
        $watermarkText = input('watermark_text/s', '');
        $watermarkConfig = input('watermark_config/a', []);
        
        // 检查图片类型
        if (!in_array($file->getMime(), $this->allowedTypes)) {
            return json(['code' => 1, 'msg' => '只支持JPG和PNG格式图片']);
        }
        
        // 检查图片尺寸
        $imageInfo = getimagesize($file->getPathname());
        if (!$imageInfo) {
            return json(['code' => 1, 'msg' => '无效的图片文件']);
        }
        
        // 限制海报尺寸为 750x1334
        if ($imageInfo[0] != 750 || $imageInfo[1] != 1334) {
            // 尝试调整图片尺寸
            try {
                $image = Image::open($file);
                $image->thumb(750, 1334, Image::THUMB_FIXED)
                    ->save($file->getPathname(), null, $this->quality);
            } catch (\Exception $e) {
                return json(['code' => 1, 'msg' => '海报尺寸必须为750x1334像素']);
            }
        }
        
        // 验证参数
        $validate = Validate::rule([
            'image' => 'require|file|fileExt:jpg,jpeg,png|fileSize:10485760',
            'name' => 'require|max:50',
            'qrcode_position.x' => 'require|number|between:0,750',
            'qrcode_position.y' => 'require|number|between:0,1334',
            'qrcode_position.width' => 'require|number|between:100,300',
            'qrcode_position.height' => 'require|number|between:100,300',
            'watermark_text' => 'max:100',
            'watermark_config.font_size' => 'number|between:12,72',
            'watermark_config.color' => 'regex:/^#[0-9a-fA-F]{6}$/',
            'watermark_config.position' => 'in:center,top,bottom,left,right'
        ]);
        
        if (!$validate->check(array_merge($_FILES, ['name' => $name, 'qrcode_position' => $qrcodePosition]))) {
            return json(['code' => 1, 'msg' => $validate->getError()]);
        }
        
        // 上传图片
        $savename = Filesystem::disk('public')->putFile('poster', $file);
        if (!$savename) {
            return json(['code' => 1, 'msg' => '上传失败']);
        }
        
        // 创建模板记录
        $template = PosterTemplate::create([
            'merchant_id' => request()->merchant_id,
            'name' => $name,
            'background_image' => $savename,
            'qrcode_position' => $qrcodePosition,
            'watermark_text' => $watermarkText,
            'watermark_config' => array_merge([
                'font_size' => 24,
                'color' => '#333333',
                'position' => 'center'
            ], $watermarkConfig)
        ]);
        
        return json(['code' => 0, 'msg' => '上传成功', 'data' => $template]);
    }
    
    /**
     * 删除模板
     */
    public function delete($id)
    {
        $template = PosterTemplate::where([
            'merchant_id' => request()->merchant_id,
            'id' => $id
        ])->find();
        
        if (!$template) {
            return json(['code' => 1, 'msg' => '模板不存在']);
        }
        
        // 删除图片文件
        Filesystem::disk('public')->delete($template->background_image);
        
        // 删除记录
        $template->delete();
        
        return json(['code' => 0, 'msg' => '删除成功']);
    }
    
    /**
     * 切换模板状态
     */
    public function toggleStatus()
    {
        $id = input('id/d', 0);
        $status = input('status/d', 0);
        
        if (!$id || !in_array($status, [1, 2])) {
            return json(['code' => 1, 'msg' => '参数错误']);
        }
        
        $template = PosterTemplate::where([
            'merchant_id' => request()->merchant_id,
            'id' => $id
        ])->find();
        
        if (!$template) {
            return json(['code' => 1, 'msg' => '模板不存在']);
        }
        
        $template->status = $status;
        $template->save();
        
        return json(['code' => 0, 'msg' => '操作成功']);
    }
    
    /**
     * 生成邀请海报
     */
    public function generate()
    {
        $templateId = input('template_id/d', 0);
        $qrcode = input('qrcode/s', '');
        
        if (!$templateId || !$qrcode) {
            return json(['code' => 1, 'msg' => '参数错误']);
        }
        
        $template = PosterTemplate::where([
            'merchant_id' => request()->merchant_id,
            'id' => $templateId
        ])->find();
        
        if (!$template) {
            return json(['code' => 1, 'msg' => '模板不存在']);
        }
        
        try {
            // 创建画布
            $backgroundImage = Image::open(public_path() . 'storage/' . $template->background_image);
            
            // 获取二维码图片
            $qrcodeImage = Image::open($qrcode);
            
            // 调整二维码大小
            $pos = $template->qrcode_position;
            $qrcodeImage->thumb($pos['width'], $pos['height'], Image::THUMB_FIXED);
            
            // 合并图片
            $backgroundImage->water(
                $qrcodeImage, 
                $pos['x'],
                $pos['y']
            );
            
            // 添加水印文字
            if (!empty($template->watermark_text)) {
                $config = $template->watermark_config;
                $font = public_path() . 'static/fonts/msyh.ttf';
                
                // 确保字体文件存在
                if (!file_exists($font)) {
                    throw new \Exception('字体文件不存在');
                }
                
                // 计算文字位置
                $fontSize = $config['font_size'] ?? 24;
                $box = imagettfbbox($fontSize, 0, $font, $template->watermark_text);
                $textWidth = abs($box[4] - $box[0]);
                $textHeight = abs($box[1] - $box[5]);
                
                // 根据配置计算坐标
                switch ($config['position'] ?? 'center') {
                    case 'top':
                        $x = (750 - $textWidth) / 2;
                        $y = $fontSize + 10;
                        break;
                    case 'bottom':
                        $x = (750 - $textWidth) / 2;
                        $y = 1334 - 10;
                        break;
                    case 'left':
                        $x = 10;
                        $y = (1334 + $textHeight) / 2;
                        break;
                    case 'right':
                        $x = 750 - $textWidth - 10;
                        $y = (1334 + $textHeight) / 2;
                        break;
                    default: // center
                        $x = (750 - $textWidth) / 2;
                        $y = (1334 + $textHeight) / 2;
                }
                
                // 添加文字
                $backgroundImage->text(
                    $template->watermark_text,
                    $font,
                    $fontSize,
                    $config['color'] ?? '#333333',
                    [$x, $y]
                );
            }
            
            // 保存合成后的图片
            $savePath = 'poster/invite_' . uniqid() . '.png';
            $savename = public_path() . 'storage/' . $savePath;
            $backgroundImage->save($savename, null, $this->quality);
            
            // 清理临时文件
            $this->cleanTempFiles();
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => [
                    'poster_url' => request()->domain() . '/storage/' . $savePath
                ]
            ]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '生成海报失败']);
        }
    }
    
    /**
     * 预览海报
     */
    public function preview()
    {
        $templateId = input('template_id/d', 0);
        
        if (!$templateId) {
            return json(['code' => 1, 'msg' => '参数错误']);
        }
        
        $template = PosterTemplate::where([
            'merchant_id' => request()->merchant_id,
            'id' => $templateId
        ])->find();
        
        if (!$template) {
            return json(['code' => 1, 'msg' => '模板不存在']);
        }
        
        try {
            // 创建示例二维码
            $qrcode = $this->createDemoQrcode();
            
            // 生成预览图
            $previewUrl = $this->generatePoster($template, $qrcode);
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => [
                    'preview_url' => $previewUrl
                ]
            ]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '生成预览图失败']);
        }
    }
    
    /**
     * 创建示例二维码
     */
    protected function createDemoQrcode()
    {
        $qrcode = new \Endroid\QrCode\QrCode('https://example.com');
        $qrcode->setSize(300);
        $qrcode->setMargin(10);
        
        $writer = new \Endroid\QrCode\Writer\PngWriter();
        $result = $writer->write($qrcode);
        
        // 保存示例二维码
        $savePath = 'poster/demo_qrcode_' . uniqid() . '.png';
        $savename = public_path() . 'storage/' . $savePath;
        file_put_contents($savename, $result->getString());
        
        return request()->domain() . '/storage/' . $savePath;
    }
    
    /**
     * 生成海报
     */
    protected function generatePoster($template, $qrcodeUrl)
    {
        try {
            // 创建画布
            $backgroundImage = Image::open(public_path() . 'storage/' . $template->background_image);
            
            // 获取二维码图片
            $qrcodeImage = Image::open($qrcodeUrl);
            
            // 调整二维码大小
            $pos = $template->qrcode_position;
            $qrcodeImage->thumb($pos['width'], $pos['height'], Image::THUMB_FIXED);
            
            // 合并图片
            $backgroundImage->water(
                $qrcodeImage, 
                $pos['x'],
                $pos['y']
            );
            
            // 添加水印文字
            if (!empty($template->watermark_text)) {
                $config = $template->watermark_config;
                $font = public_path() . 'static/fonts/msyh.ttf';
                
                // 确保字体文件存在
                if (!file_exists($font)) {
                    throw new \Exception('字体文件不存在');
                }
                
                // 计算文字位置
                $fontSize = $config['font_size'] ?? 24;
                $box = imagettfbbox($fontSize, 0, $font, $template->watermark_text);
                $textWidth = abs($box[4] - $box[0]);
                $textHeight = abs($box[1] - $box[5]);
                
                // 根据配置计算坐标
                switch ($config['position'] ?? 'center') {
                    case 'top':
                        $x = (750 - $textWidth) / 2;
                        $y = $fontSize + 10;
                        break;
                    case 'bottom':
                        $x = (750 - $textWidth) / 2;
                        $y = 1334 - 10;
                        break;
                    case 'left':
                        $x = 10;
                        $y = (1334 + $textHeight) / 2;
                        break;
                    case 'right':
                        $x = 750 - $textWidth - 10;
                        $y = (1334 + $textHeight) / 2;
                        break;
                    default: // center
                        $x = (750 - $textWidth) / 2;
                        $y = (1334 + $textHeight) / 2;
                }
                
                // 添加文字
                $backgroundImage->text(
                    $template->watermark_text,
                    $font,
                    $fontSize,
                    $config['color'] ?? '#333333',
                    [$x, $y]
                );
            }
            
            // 保存合成后的图片
            $savePath = 'poster/invite_' . uniqid() . '.png';
            $savename = public_path() . 'storage/' . $savePath;
            $backgroundImage->save($savename, null, $this->quality);
            
            return request()->domain() . '/storage/' . $savePath;
        } catch (\Exception $e) {
            throw new \Exception('生成海报失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 清理临时文件
     */
    protected function cleanTempFiles()
    {
        $storage = public_path() . 'storage/poster/';
        $files = glob($storage . '{demo_qrcode_*,preview_*,invite_*}.png', GLOB_BRACE);
        
        foreach ($files as $file) {
            if (time() - filemtime($file) > 3600) { // 清理1小时前的临时文件
                @unlink($file);
            }
        }
    }
} 